package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-manager/cache"
	"post-manager/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var posts []models.Post
	//缓存中读取分页的数据
	redis_list_key := "list_page_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {

		models.DB.Offset(offset).Limit(size).Debug().Find(&posts)       //从mysql读取数据
		jsonData, _ := json.Marshal(posts)                              //转换为json数据
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2) //保存到缓存中

	} else {
		json.Unmarshal([]byte(result), &posts)
	}
	var total int64
	models.DB.Model(&models.Post{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"total": total,
		"data":  posts,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var post models.Post

	//缓存中读取数据
	redis_list_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		models.DB.Where("id = ?", id).First(&post)                      //从mysql读取数据
		jsonData, _ := json.Marshal(post)                               //转换为json数据
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2) //保存到缓存中

	} else {
		json.Unmarshal([]byte(result), &post)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": post,
	})
	return
}
